package com.greejoy.score.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.greejoy.score.MyApplication;
import com.greejoy.score.R;
import com.greejoy.score.domain.Place;
import com.greejoy.score.domain.PlaceBody;
import com.greejoy.score.service.HttpService;
import com.greejoy.score.utils.DimUtils;
import com.greejoy.score.utils.ZipUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener {

    private MyApplication app;
    private Retrofit retrofit;
    private HttpService httpService;

    private LinearLayout ll_place_list;
    private Button btn_download;

    private GifImageView giv_ws_loading;

    private MediaPlayer mediaPlayer = new MediaPlayer();

    private List<TextView> tvPlaceList;
    private Long currPlaceId;
    private Long currRegisterId;
    private String filesPath;

    private Handler handler = new Handler(msg -> {
        switch (msg.what) {
            case 0:
                Toast.makeText(MusicActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                btn_download.setEnabled(true);
                btn_download.setText("同步下载");
                break;
            case 1:
                btn_download.setEnabled(false);
                btn_download.setText("正在下载... \n" + (msg.obj != null ? msg.obj : "0MB"));
                break;
            case 2:
                Toast.makeText(MusicActivity.this, "下载完成，开始解压...", Toast.LENGTH_SHORT).show();
                btn_download.setText("正在解压...");
                break;
            case 3:
                Toast.makeText(MusicActivity.this, "解压完成...", Toast.LENGTH_SHORT).show();
                btn_download.setEnabled(true);
                btn_download.setText("同步下载");
                break;
        }
        return false;
    });

    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(getString(R.string.broadcast_action))){
                String msg = intent.getStringExtra("msg");
                String filename = intent.getStringExtra("filename");
                Long placeId = intent.getLongExtra("placeId", -1l);
                Long registerId = intent.getLongExtra("registerId", -1l);
                Boolean loop = intent.getBooleanExtra("loop", false);
                Integer volume = intent.getIntExtra("volume", -1);
                switch (msg){
                    case "showWsLoading":
                        giv_ws_loading.setVisibility(View.VISIBLE);
                        break;
                    case "hideWsLoading":
                        giv_ws_loading.setVisibility(View.INVISIBLE);
                        break;
                    case "playMusic":
                        if(!placeId.equals(currPlaceId) && currPlaceId != -1l){
                            break;
                        }
                        if(registerId.equals(-1) || !registerId.equals(currRegisterId)){
                            currRegisterId = registerId;
                            String musicPath = filesPath + "/music/" + filename;
                            try {
                                mediaPlayer.reset();
                                mediaPlayer.setDataSource(musicPath);
                                mediaPlayer.prepare();
                            } catch (IOException e) {
                                e.printStackTrace();
                                Log.d("zhuwei", e.getMessage());
                            }
                        }
                        mediaPlayer.start();
                        break;
                    case "pauseMusic":
                        if(!placeId.equals(currPlaceId) && currPlaceId != -1l){
                            break;
                        }
                        mediaPlayer.pause();
                        break;
                    case "replayMusic":
                        if(!placeId.equals(currPlaceId) && currPlaceId != -1l){
                            break;
                        }
                        mediaPlayer.seekTo(0);
                        mediaPlayer.start();
                        break;
                    case "setLoop":
                        if(!placeId.equals(currPlaceId) && currPlaceId != -1l){
                            break;
                        }
                        mediaPlayer.setLooping(loop);
                        break;
                    case "setVolume":
                        if(!placeId.equals(currPlaceId) && currPlaceId != -1l){
                            break;
                        }
                        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
                        break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(getString(R.string.broadcast_action));
        registerReceiver(myBroadcastReceiver, intentFilter);

        app = MyApplication.getInstance();
        String httpUrl = app.dataMap.get("httpUrl");
        retrofit = new Retrofit.Builder().baseUrl(httpUrl).build();
        httpService = retrofit.create(HttpService.class);

        ll_place_list = findViewById(R.id.ll_place_list);
        btn_download = findViewById(R.id.btn_download);
        btn_download.setOnClickListener(this);

        giv_ws_loading = findViewById(R.id.giv_ws_loading);

        filesPath = getExternalFilesDir("").getAbsolutePath();

    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshPlaceList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_download){

            Message msg = Message.obtain();
            msg.what = 1;
            handler.sendMessage(msg);

            String httpUrl = app.dataMap.get("httpUrl");
            String url = httpUrl + "gyms/app/downloadMusic?key=" + getString(R.string.server_key);

            File file = new File(filesPath + "/music");
            if(file.exists()){
                String filenames = Arrays.stream(file.listFiles()).map(m -> m.getName()).collect(Collectors.joining(","));
                url = url + "&filenames=" + filenames;
            }

            Request request = new Request.Builder().url(url).build();
            OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.MINUTES).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    // 下载失败
                    e.printStackTrace();
                    Log.d("zhuwei", "download onFailure");
                    Log.d("zhuwei",e.getMessage());
                    Message msg = Message.obtain();
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    try {
                        is = response.body().byteStream();
                        File file = new File(filesPath + "/music.zip");
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        long show = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            if((sum - show) > 1024 * 100){
                                show = sum;
                                Message msg = Message.obtain();
                                msg.what = 1;
                                msg.obj = String.format("%.1fMB", show / 1024 / 1024.0);
                                handler.sendMessage(msg);
                            }
                        }
                        fos.flush();

                        // 下载完成
                        Message msg2 = Message.obtain();
                        msg2.what = 2;
                        handler.sendMessage(msg2);
                        String musicPath = filesPath + "/music";

                        // 解压
                        ZipUtils.upZipFile(file, musicPath);
                        Message msg3 = Message.obtain();
                        msg3.what = 3;
                        handler.sendMessage(msg3);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("zhuwei","download failed");
                        Log.i("zhuwei","===" + e.getMessage());
                        Message msg = Message.obtain();
                        msg.what = 0;
                        handler.sendMessage(msg);
                    } finally {
                        if (is != null){
                            is.close();
                        }
                        if (fos != null){
                            fos.close();
                        }
                    }
                }

            });

        }
    }

    private void refreshPlaceList(){
        retrofit2.Call<ResponseBody> call = httpService.getPlaceList(getString(R.string.server_key));
        call.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                if(response.isSuccessful()){
                    try {
                        String bodyStr = response.body().string();
                        PlaceBody placeBody = JSON.parseObject(bodyStr, PlaceBody.class);
                        List<Place> placeList = placeBody.getData();
                        ll_place_list.removeAllViews();
                        tvPlaceList = new ArrayList<>();

                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        int dp10 = DimUtils.dip2px(MusicActivity.this, 10);

                        TextView tv0 = new TextView(MusicActivity.this);
                        tv0.setId(View.generateViewId());
                        tv0.setText("全部");
                        tv0.setBackgroundColor(getColor(R.color.gray));

                        params.setMargins(dp10, dp10, dp10, dp10);
                        tv0.setLayoutParams(params);
                        tv0.setPadding(dp10 * 2, dp10, dp10 * 2, dp10);
                        tv0.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                for (TextView view : tvPlaceList) {
                                    view.setBackgroundColor(getColor(R.color.gray));
                                }
                                v.setBackgroundColor(getColor(R.color.blue));
                                currPlaceId = -1l;
                            }
                        });
                        tvPlaceList.add(tv0);
                        ll_place_list.addView(tv0);

                        for (Place place : placeList) {
                            TextView tv = new TextView(MusicActivity.this);
                            int id = View.generateViewId();
                            tv.setId(id);
                            tv.setText(place.getName());
                            tv.setBackgroundColor(getColor(R.color.gray));
                            params.setMargins(dp10, dp10, dp10, dp10);
                            tv.setLayoutParams(params);
                            tv.setPadding(dp10 * 2, dp10, dp10 * 2, dp10);
                            tv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    for (TextView view : tvPlaceList) {
                                        view.setBackgroundColor(getColor(R.color.gray));
                                    }
                                    v.setBackgroundColor(getColor(R.color.blue));
                                    currPlaceId = place.getId();
                                }
                            });
                            tvPlaceList.add(tv);
                            ll_place_list.addView(tv);
                        }

                    } catch (Exception e) {
                        Toast.makeText(MusicActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();;
                    }
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                Toast.makeText(MusicActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
}